<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    enablePullDownRefresh: false,
    navigationBarTitleText: '密码修改',
  },
}
</route>
<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view class="password-page">
    <wd-navbar title="修改密码" :bordered="false" safeAreaInsetTop>
      <template #left>
        <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
      </template>
    </wd-navbar>
    <view class="password-inner">
      <wd-form ref="formRef" :model="form" :rules="rules">
        <view class="card">
          <th-form-item v-if="type == 2" label="账号">
            <wd-input
              type="text"
              v-model="form.username"
              prop="username"
              placeholder="请输入账号"
              no-border
              style="width: 98%"
            />
          </th-form-item>
          <th-form-item label="原始密码">
            <wd-input
              type="text"
              v-model="form.password"
              prop="password"
              placeholder="请输入原始密码"
              no-border
              showPassword
              style="width: 98%"
            />
          </th-form-item>
        </view>
        <view class="card">
          <th-form-item label="新密码">
            <wd-input
              type="text"
              v-model="form.newpassword1"
              prop="newpassword1"
              placeholder="请输入新密码"
              no-border
              showPassword
              style="width: 98%"
            />
          </th-form-item>
          <th-form-item label="确认密码">
            <wd-input
              type="text"
              v-model="form.newpassword2"
              prop="newpassword2"
              placeholder="请输入确认密码"
              no-border
              showPassword
              style="width: 98%"
            />
          </th-form-item>
        </view>
      </wd-form>
      <view class="global_submit_item">
        <button class="global_submit bg-blue" @click="onSubmit">确认修改</button>
      </view>
    </view>
  </view>
  <!-- <form>
			<view class="cu-form-group" v-if="model === 'modify'">
				<view class="title required">账&#8194;&#8194;&#8194;&#8194;号</view>
				<input type="text" :value="params.username" @input="onInput($event,'username')" placeholder="请输入账号" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="title required">原始密码</view>
				<input type="password" :value="params.password" @input="onInput($event,'password')" placeholder="请输入原密码" name="input"></input>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title required">新&#8194;密&#8194;码</view>
				<input type="password" :value="params.newPassword" @input="onInput($event,'newPassword')" placeholder="请输入新密码" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="title required">确认密码</view>
				<input type="password" :value="params.confirmPassword" @input="onInput($event,'confirmPassword')" placeholder="再次输入新密码" name="input"></input>
			</view>
		</form> -->
</template>
<script lang="ts" setup>
import cache from '@/utils/cache';
import { useSetting } from '@/stores/setting';
import { ClearClientId, savePassword, registerPassword } from '@/service/user';

const setting = useSetting();
const type = ref(1);
// 提交表单数据
const form = reactive({
  username: null,
  password: '',
  newpassword1: '',
  newpassword2: '',
});

const rules: any = computed(() => {
  return {
    username: [{ required: type.value === 2, message: '账号不能为空' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    newpassword1: [
      { required: true, min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间' },
    ],
    newpassword2: [
      { required: true, min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间' },
    ],
  };
});
const formRef: any = ref({});
const formValidate = () => {
  console.log('validate');
  let text = '';
  if (type.value === 2 && !form.username) {
    text = '请输入账号';
  }
  if (form.newpassword1 != form.newpassword2) {
    text = '确认密码与新密码不一致，请重新输入';
  }
  // password: '',
  // newpassword1: '',
  // newpassword2: '',
  if (text) {
    uni.showModal({
      title: '提示',
      content: text,
    });
    return false;
  }
  return true;
};
const onSubmit = () => {
  formRef.value.validate().then(({ valid, errors }) => {
    if (!valid) return false;
    if (formValidate())
      uni.showModal({
        title: '提示',
        content: '是否修改密码',
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            uni.showLoading({
              mask: true,
            });
            (type.value === 1 ? savePassword(form) : registerPassword(form))
              .then(async (res) => {
                if (res.code == 0) {
                  uni.showToast({
                    mask: true,
                    title: `修改成功`,
                    icon: 'none',
                  });
                  if (type.value === 1) {
                    // #ifdef APP-PLUS
                    try {
                      await ClearClientId(plus.push.getClientInfo().clientid);
                    } catch (error) {
                      console.log(error, 2222);
                    }
                    // #endif
                    cache.remove('token');
                    uni.redirectTo({ url: '/pages/login/login' });
                    // #ifdef APP-PLUS
                    plus.runtime.setBadgeNumber(-1);
                    plus.runtime.setBadgeNumber(0);
                    //  #endif
                  } else {
                    goBack();
                  }
                } else {
                  uni.showToast({
                    mask: true,
                    title: `修改失败，失败原因：${res.msg}`,
                    icon: 'none',
                  });
                }
              })
              .finally(() => {
                uni.hideLoading();
              });
          }
        },
      });
  });
};

const goBack = () => {
  uni.navigateBack();
};

// const init = (id?) => {
//   console.log('id', id);
// };
onLoad((options) => {
  console.log('options', options);
  if (options.type) {
    type.value = Number(options.type);
  }
  if (options.username) {
    form.username = options.username;
  }
  // init();
});
</script>
<style scoped lang="scss">
.password-page {
  height: 100vh;
  background-color: #f8f8f8;
  .password-inner {
    padding: 20rpx 0;
  }
  .card {
    margin-bottom: 20px;
    background-color: white;
  }
  .global_submit_item {
    padding: 20rpx 30rpx;
    .global_submit {
      color: white;
      background-color: #409eff;
    }
  }
}
</style>
<!-- <script>
	import { modifyPassword } from '@/utils/api/user.js'
	import { validate } from '@/utils/tools.js'

	export default{
		data(){
			return {
				loading:false,
				params:{
					username:uni.getStorageSync("username") || this.$store.state.info.username || '',
					password:'',
					newPassword:'',
					confirmPassword:''
				},
				rules:{
					username: { required:true, message:'请输入账号'},
					password: { required:true, message:'请输入原始密码'},
					newPassword: { required:true, message:'请输入新密码'},
				    confirmPassword: { required:true, message:'请输入确认密码' }
				},
				model:''
			}
		},
		methods:{
			onInput(e,k) {
				this.params[k] = e.detail.value
			},
			submit(){
				if(this.loading) return
				this.loading = true
				const {params} = this
				if(this.model === 'modify'){
					this.rules.username.required = true
				}else{
					this.rules.username.required = false
				}

				if(!validate(params,this.rules)) return
				if(this.params.newPassword !== this.params.confirmPassword){
					uni.showModal({
						title:'提示',
						content:'两次密码输入不一样',
						showCancel:false
					})
					this.loading = false
					return
				}

				this.$ask('您确定要修改密码吗？').then(res=>{
					uni.showLoading({
						title:'保存中',
						mask:true
					})
					modifyPassword(this.params).then(res=>{
						if (res.code != 0) {
							uni.hideLoading();
							this.$error(res.msg);
							return false;
						}
						this.$ok('密码修改成功')
						setTimeout(()=>{
							uni.removeStorage('storage_token')
							this.$store.commit('setToken','')
							uni.reLaunch({
								url: '/pages/login/login',
								animationType: 'pop-in',
								animationDuration: 200
							})
						},1500)
					}).catch(err=>{
						uni.hideLoading()
						this.loading= false
						this.$error(err.msg)
					})
				}).catch(err=>{
					this.loading= false
					this.$error(err.data.msg)
				})
			}
		},
		onLoad(option) {
			this.model = option.model
		}
	}
</script> -->
